﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using TheGameClient.Webservices;

namespace TheGameClient
{
	public partial class DlgSaveConnection
	{
		private readonly List<ulong> _connected;
		private List<SavedConnection> _connections;

		public DlgSaveConnection(List<ulong> connectedSystems)
		{
			InitializeComponent();
			_connections = new List<SavedConnection>();
			_connected = connectedSystems;
			//Fill dropdown with existing connections
			App.Client.Connect_GetConnectionsCompleted += ClientConnectGetConnectionsCompleted;
			App.Client.Connect_GetConnectionsAsync(App.InternalSessionId);
		}

		private void ClientConnectGetConnectionsCompleted(object sender, Connect_GetConnectionsCompletedEventArgs e)
		{
			App.Client.Connect_GetConnectionsCompleted -= ClientConnectGetConnectionsCompleted;
			if (e.Error != null)
			{
				App.ServerError();
				return;
			}
			if (e.Result != null)
			{
				_connections = e.Result.OrderBy(it => it.Name).ToList();
				cmbExistingConnections.ItemsSource = _connections;
			}
		}

		private void OkButtonClick(object sender, RoutedEventArgs e)
		{
			string connectionName = txtConnectionName.Text;
			if (string.IsNullOrEmpty(connectionName))
				return;

			var dupeCheck = (from c in _connections where c.Name == connectionName select c).FirstOrDefault();
			SavedConnection toModify;
			if (dupeCheck != null)
			{
				toModify = dupeCheck;
				if (_connected.Count == 0)
				{
					if (
						MessageBox.Show(
							"Overwriting an existing connection with zero connected nodes will delete this saved connection. Continue?",
							"Warning", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
						return;
					toModify.Route.Clear();
				}
				else
				{
					if (
						MessageBox.Show("This will overwrite the existing connection with name '" + dupeCheck.Name + "'.\nContinue?",
						                "Warning", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
						return;
					toModify.Route = _connected;
				}
			}
			else
			{
				if (_connected.Count == 0)
					return;
				toModify = new SavedConnection {Id = Guid.NewGuid().ToLong(), Name = connectionName, Route = _connected};
			}

			App.Client.Connect_SaveConnectionCompleted += ClientConnectSaveConnectionCompleted;
			App.Client.Connect_SaveConnectionAsync(App.InternalSessionId, toModify);
		}

		private void ClientConnectSaveConnectionCompleted(object sender, Connect_SaveConnectionCompletedEventArgs e)
		{
			App.Client.Connect_SaveConnectionCompleted -= ClientConnectSaveConnectionCompleted;
			if (e.Error != null)
			{
				App.ServerError();
				return;
			}
			if (!e.Result)
				MessageBox.Show("Error saving connection.");
			else
				DialogResult = true;
		}

		private void CancelButtonClick(object sender, RoutedEventArgs e)
		{
			DialogResult = false;
		}

		private void CmbExistingConnectionsSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (cmbExistingConnections.SelectedItem != null && cmbExistingConnections.SelectedItem is SavedConnection)
				txtConnectionName.Text = ((SavedConnection) cmbExistingConnections.SelectedItem).Name;
		}

		private void TxtConnectionNameTextChanged(object sender, TextChangedEventArgs e)
		{
			SavedConnection conn =
				(from c in (cmbExistingConnections.ItemsSource as List<SavedConnection>)
				 where c.Name == txtConnectionName.Text
				 select c).FirstOrDefault();
			if (conn != null)
				cmbExistingConnections.SelectedItem = conn;
			else
				cmbExistingConnections.SelectedIndex = -1;
		}
	}
}